from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity

from app import redis_client, LogService
from app.models.passenger_lib import Passenger, isAvailable
from presenter import PassengerPresenter
from utils import StateCode, create_response, checkMobile, checkIdCard, checkBankCard

register_bp = Blueprint('register', __name__)


@register_bp.route('/register', methods=['POST'])
def register():
    data = request.json
    account = data.get('account')
    password = data.get('password')
    mobile_no = data.get('mobileNo')
    mobile_code = data.get('mobileCode')
    id_card_no = data.get('idCardNo')
    bank_card_no = data.get('bankCard')

    if not account or not password:
        return jsonify(create_response(StateCode.PARAMS_ERROR)), 400

    if not checkMobile(mobile_no):
        return jsonify(create_response(StateCode.MOBILE_ERROR)), 400

    if not verifyCode(mobile_no, mobile_code):
        return jsonify(create_response(StateCode.MOBILE_CODE_ERROR)), 400

    if not checkIdCard(id_card_no):
        return jsonify(create_response(StateCode.ID_CARD_ERROR)), 400

    if isAvailable(account):
        return jsonify(create_response(StateCode.USER_ALREADY_EXISTS)), 400

    if not checkBankCard(bank_card_no):
        return jsonify(create_response(StateCode.BANK_CARD_ERROR)), 400

    new_passenger = Passenger.create(data=data)
    access_token = create_access_token(identity=new_passenger.id)
    user_presenter = PassengerPresenter(new_passenger, {"token": access_token}).as_dict()
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=user_presenter)), 200


@register_bp.route('/auth', methods=['GET'])
@jwt_required()
def auth():
    current_user = get_jwt_identity()
    user = Passenger.query.get(current_user)
    if not user:
        return jsonify(create_response(StateCode.USER_NOT_FOUND)), 400
    user_presenter = PassengerPresenter(user, {}).as_dict()
    LogService.log()

    return jsonify(create_response(code=StateCode.SUCCESS, data=user_presenter)), 200


def verifyCode(mobile_no, code):
    stored_code = redis_client.get(mobile_no)
    return stored_code == code
